package com.li.youhappygo.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.li.youhappygo.exception.GlobalException;
import com.li.youhappygo.mapper.SysUserMapper;
import com.li.youhappygo.model.dto.LoginDto;
import com.li.youhappygo.model.entity.system.SysUser;
import com.li.youhappygo.model.vo.common.ResultCode;
import com.li.youhappygo.model.vo.system.LoginVo;
import com.li.youhappygo.service.SysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysServiceImpl implements SysService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        QueryWrapper<SysUser> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq("username",username);
//        List<SysUser> sysUserList = sysUserMapper.selectList(wrapperUser);
//        SysUser sysUser=sysUserList.get(0);
        SysUser sysUser = sysUserMapper.selectOne(wrapperUser);
//        String password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if(!sysUser.getPassword().equals(password)){
            throw new GlobalException(ResultCode.LOGIN_ERROR);
        }
        String token = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set("user:login:"+token, JSONObject.toJSONString(sysUser),30, TimeUnit.MINUTES);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public void loginOut(String token) {
        redisTemplate.delete("user:login:"+token);
    }

    @Override
    public SysUser getUserInfo(String token) {
        String sysUserString = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(sysUserString, SysUser.class);
        return sysUser;
    }
}
